//
//  MXPopupView.swift
//  d11
//
//  Created by peale_pro on 2019/7/10.
//  Copyright © 2019年 Tech_001. All rights reserved.
//

import UIKit
typealias MXPopupViewBtnSeltSeltBlock = (_ index:Int) -> Void
typealias MXPopupViewPlatformSeltBlock2 = (_ dict: [String:Any],_ index:Int) -> Void
class MXPopupView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {
    var arrayList : [[String:Any]]? //数据列表
    var type : Int = 0
    var selectIndex = -1
    var selectDict : [String:Any]?
  
    var mXPopupViewBtnSeltSeltBlock: MXPopupViewBtnSeltSeltBlock?
  
    func callClickBlock2(_ block: @escaping MXPopupViewBtnSeltSeltBlock) {
        mXPopupViewBtnSeltSeltBlock = block
    }
    var mXPopupViewPlatformSeltBlock2: MXPopupViewPlatformSeltBlock2?
    func callClickBlock(_ block: @escaping MXPopupViewPlatformSeltBlock2) {
        mXPopupViewPlatformSeltBlock2 = block
    }
    var isHorizontalScreen :Bool = false
    var gamePopupView : MXGamePopupView?
    var minusHeight = 0.0
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = CGSize(width: (110-10)/2, height: 157.5/3)
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumInteritemSpacing = 0
        //  }
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        // layout.headerReferenceSize = CGSize.init(width: (kScreenWidth-20)/4, height: 87.5)
        // 设置分区头视图和尾视图宽高
        //    layout.headerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        //    layout.footerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        var collView = UICollectionView.init(frame: CGRect(x:0, y:0, width:110-10, height:157.5-self.minusHeight), collectionViewLayout: layout)
        
        
        if collView.responds(to:#selector(setter: UIView.layoutMargins)) {
            collView.layoutMargins = .zero;
        }
        
        collView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth.union(UIView.AutoresizingMask.flexibleHeight)
        collView.register(MXPopupViewItemCell.self, forCellWithReuseIdentifier: "MXPopupViewItemCell")
        //        collView.register(HelperListHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HelperListHeadView1")
        collView.showsVerticalScrollIndicator = false
        collView.showsHorizontalScrollIndicator = false
        collView.delegate = self
        collView.dataSource = self
        collView.backgroundColor = UIColor.white
        collView.layer.cornerRadius = 5;
        collView.layer.masksToBounds = true
        // collView.backgroundColor = UIColor.red
        return collView
    }()
    
    convenience init(gameArray:[[String:Any]]?,top:CGFloat,right:CGFloat,isHorizontalScreen:Bool) {
        self.init(frame: UIScreen.main.bounds)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        //        let effecView = UIHelper.showBlurEffect(isClick:true)
        //       window.addSubview(effecView)
        self.backgroundColor = UIColor.clear
        window.addSubview(self)
        self.arrayList = []
        if gameArray != nil{
            self.arrayList = gameArray
        }
        self.isHorizontalScreen = isHorizontalScreen
        if kScreenWidth <= 320 && self.isHorizontalScreen == true{
            self.minusHeight = 157.5/3+10
        }
        self.showMorePopView(gameArray: self.arrayList, top: top, right: right)
    }
    @objc func closePageView() -> Void {
        self.removeFromSuperview()
    }

    //web导航栏更多弹窗
    func showMorePopView(gameArray:[[String:Any]]?,top:CGFloat,right:CGFloat){
        let bgView :UIView  = UIView.init()
       // bgView.backgroundColor = RGBAlpa(0,0,0,0)
        bgView.backgroundColor = UIColor.clear
        bgView.tag = 2001
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
////        let effecView = UIHelper.showBlurEffect(isClick:true)
////       window.addSubview(effecView)
        self.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
     let arrowIV  = UIImageView.init(image: UIImage.init(named: "icon_top_arrow"))
        self.addSubview(arrowIV)
        arrowIV.snp.makeConstraints { (make) in
            make.width.equalTo(15)
            make.right.equalToSuperview().offset((-right))
            make.top.equalToSuperview().offset(top)
            make.height.equalTo(10)
        }
        //
        let bgWidth = 110
        let whiteView :UIView  = UIView.init(frame: UIScreen.main.bounds)
        whiteView.backgroundColor = HexRGBAlpha(0x424242, 1)
        whiteView.layer.cornerRadius = 5;
        whiteView.layer.masksToBounds = true
        self.addSubview(whiteView)
        whiteView.snp.makeConstraints { (make) in
            make.width.equalTo(bgWidth)
            make.centerX.equalTo(arrowIV.snp.centerX)
            make.top.equalTo(arrowIV.snp.bottom).offset(-1)
            make.height.equalTo(315-self.minusHeight)
        }
        
       let fullBtn = UIButton.init(type: .custom)
        fullBtn.setTitleColor(UIColor.white, for: .normal)
        fullBtn.setTitle("全屏", for: .normal)
        fullBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        fullBtn.tag = 1001
        fullBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        whiteView.addSubview(fullBtn)
        fullBtn.snp.makeConstraints { (make) in
            make.width.equalTo(bgWidth/2)
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(25)
        }
        let lineView = UIView.init()
        lineView.backgroundColor = HexRGBAlpha(0xf6f8fa, 1)
        whiteView.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.width.equalTo(0.5)
            make.left.equalTo(fullBtn.snp.right)
            make.top.equalToSuperview().offset(5)
            make.height.equalTo(15)
        }
        
        let closeBtn = UIButton.init(type: .custom)
        closeBtn.setTitleColor(UIColor.white, for: .normal)
        closeBtn.setTitle("关闭", for: .normal)
        closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        closeBtn.tag = 1002
        closeBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        whiteView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.width.equalTo(bgWidth/2)
            make.left.equalTo(lineView.snp.right)
            make.top.equalToSuperview()
            make.height.equalTo(25)
        }
        let topHeight = 120
        let topBgView = UIView.init()
        topBgView.backgroundColor = UIColor.white
        topBgView.layer.cornerRadius = 5;
        topBgView.layer.masksToBounds = true
        whiteView.addSubview(topBgView)
        topBgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
            make.top.equalTo(fullBtn.snp.bottom)
            make.height.equalTo(topHeight)
        }
        
        let itemHeight = (topHeight/2)
        let ckBtn  = UIButton.init(type: .custom)
        ckBtn.tag = 1003
        ckBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        topBgView.addSubview(ckBtn)
        ckBtn.snp.makeConstraints { (make) in
            make.width.equalTo((bgWidth-10)/2)
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(itemHeight)
        }
        let gridImgView1 = UIImageView.init(image: imageNamed("icon_home_ck"))
        ckBtn.addSubview(gridImgView1)
        gridImgView1.snp.makeConstraints{(make) in
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(6)
        }
        
        let gridLabel1 = UILabel.init()
        gridLabel1.font = UIFont.systemFont(ofSize: 11)
        gridLabel1.textColor = HexRGBAlpha(0x747474, 1)
        gridLabel1.textAlignment = .center
        gridLabel1.text = "存款"
        ckBtn.addSubview(gridLabel1)
        gridLabel1.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(15)
            make.centerX.equalToSuperview()
            make.top.equalTo(gridImgView1.snp.bottom)
        }
        
        
        let lineViewY1 = UIView.init()
        lineViewY1.backgroundColor = HexRGBAlpha(0xffc569, 0.8)
        topBgView.addSubview(lineViewY1)
        lineViewY1.snp.makeConstraints{(make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(ckBtn).offset(-20)
            make.top.equalToSuperview().offset(10)
            make.width.equalTo(0.5)
        }
        
        let lineViewX1 = UIView.init()
        lineViewX1.backgroundColor = HexRGBAlpha(0xffc569, 0.8)
        topBgView.addSubview(lineViewX1)
        lineViewX1.snp.makeConstraints{(make) in
            make.left.equalToSuperview().offset(10)
            make.height.equalTo(0.5)
            make.top.equalTo(ckBtn.snp.bottom)
            make.width.equalTo(((bgWidth-10)/2)-20)
        }
        
        let lineViewX2 = UIView.init()
        lineViewX2.backgroundColor = HexRGBAlpha(0xffc569, 0.8)
        topBgView.addSubview(lineViewX2)
        lineViewX2.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(0.5)
            make.top.equalTo(lineViewX1.snp.top)
            make.width.equalTo(((bgWidth-10)/2)-20)
        }
        
        let lineViewY2 = UIView.init()
        lineViewY2.backgroundColor = HexRGBAlpha(0xffc569, 0.8)
        topBgView.addSubview(lineViewY2)
        lineViewY2.snp.makeConstraints{(make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(ckBtn).offset(-20)
            make.bottom.equalToSuperview().offset(-10)
            make.width.equalTo(0.5)
        }
        
        
        let qkBtn  = UIButton.init(type: .custom)
        qkBtn.tag = 1004
        qkBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        topBgView.addSubview(qkBtn)
        qkBtn.snp.makeConstraints { (make) in
            make.width.equalTo((bgWidth-10)/2)
            make.left.equalTo(lineViewY1.snp.right)
            make.top.equalTo(ckBtn.snp.top)
            make.height.equalTo(itemHeight)
        }
        let gridImgView2 = UIImageView.init(image: imageNamed("icon_home_qk"))
        qkBtn.addSubview(gridImgView2)
        gridImgView2.snp.makeConstraints{(make) in
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(6)
        }
        
        let gridLabel2 = UILabel.init()
        gridLabel2.font = UIFont.systemFont(ofSize: 11)
        gridLabel2.textColor = HexRGBAlpha(0x747474, 1)
        gridLabel2.textAlignment = .center
        gridLabel2.text = "取款"
        qkBtn.addSubview(gridLabel2)
        gridLabel2.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(15)
            make.centerX.equalToSuperview()
            make.top.equalTo(gridImgView2.snp.bottom)
        }
        
        let zzBtn  = UIButton.init(type: .custom)
        zzBtn.tag = 1005
        zzBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        topBgView.addSubview(zzBtn)
        zzBtn.snp.makeConstraints { (make) in
            make.width.equalTo((bgWidth-10)/2)
            make.left.equalToSuperview()
            make.top.equalTo(ckBtn.snp.bottom)
            make.height.equalTo(itemHeight)
        }
        let gridImgView3 = UIImageView.init(image: imageNamed("icon_home_zz"))
        zzBtn.addSubview(gridImgView3)
        gridImgView3.snp.makeConstraints{(make) in
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(6)
        }
        
        let gridLabel3 = UILabel.init()
        gridLabel3.font = UIFont.systemFont(ofSize: 11)
        gridLabel3.textColor = HexRGBAlpha(0x747474, 1)
        gridLabel3.textAlignment = .center
        gridLabel3.text = "转账"
        zzBtn.addSubview(gridLabel3)
        gridLabel3.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(15)
            make.centerX.equalToSuperview()
            make.top.equalTo(gridImgView3.snp.bottom)
        }
        
        
        let zdBtn  = UIButton.init(type: .custom)
        zdBtn.tag = 1006
        zdBtn.addTarget(self, action:  #selector(btnClick(_:)), for: .touchUpInside)
        topBgView.addSubview(zdBtn)
        zdBtn.snp.makeConstraints { (make) in
            make.width.equalTo((bgWidth-10)/2)
            make.left.equalTo(lineViewY2.snp.right)
            make.top.equalTo(ckBtn.snp.bottom)
            make.height.equalTo(itemHeight)
        }
        let gridImgView4 = UIImageView.init(image: imageNamed("icon_home_zd"))
        zdBtn.addSubview(gridImgView4)
        gridImgView4.snp.makeConstraints{(make) in
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(6)
        }
        
        let gridLabel4 = UILabel.init()
        gridLabel4.font = UIFont.systemFont(ofSize: 11)
        gridLabel4.textColor = HexRGBAlpha(0x747474, 1)
        gridLabel4.textAlignment = .center
        gridLabel4.text = "投注记录"
        zdBtn.addSubview(gridLabel4)
        gridLabel4.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(15)
            make.centerX.equalToSuperview()
            make.top.equalTo(gridImgView4.snp.bottom)
        }
        
        whiteView.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
            make.top.equalTo(topBgView.snp.bottom).offset(5)
            make.height.equalTo(157.5-self.minusHeight)
        }
//        self.collectionView.reloadData()
//        let scoHeight = 157.5
//       let scrollView = UIScrollView.init()
//        scrollView.backgroundColor = UIColor.white
//        scrollView.layer.cornerRadius = 5;
//        scrollView.layer.masksToBounds = true
//    var lineNum = 0
//    if (gameArray?.count ?? 0) > 0 {
//       lineNum = (gameArray?.count ?? 0) / 2
//        if (gameArray?.count ?? 0) % 2 != 0 {
//            lineNum = (gameArray?.count ?? 0) / 2 + 1
//        }
//    }
    
//    scrollView.contentSize = CGSize(width: bgWidth-10, height: Int(157.5/3) * lineNum)
//        whiteView.addSubview(scrollView)
//        scrollView.snp.makeConstraints { (make) in
//            make.width.equalToSuperview().offset(-10)
//            make.centerX.equalToSuperview()
//            make.top.equalTo(topBgView.snp.bottom).offset(5)
//            make.height.equalTo(scoHeight)
//        }
//        //157.5
//        // 0 1 = 0
//        //   2 3 = 1
//        //   4 5 = 2
//        //   6 7 = 3
//        // 1%2 = 0  左
//        // 2%2 = 1。右
//        // 3%2 = 0
//        for (index,value) in gameArray!.enumerated() {
//            let currNum = index+1      //当前
//            let currLine = index/2 //行
//        }
//
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        return UICollectionReusableView.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MXPopupViewItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MXPopupViewItemCell", for: indexPath) as! MXPopupViewItemCell
        let dict:[String:Any] = self.arrayList?[indexPath.row] ?? [:]
        var isSelect = false
        if indexPath.row ==  self.selectIndex {
            isSelect = true
        }
        cell.setData(imgUrl: dict["f_imgNameIOS"] as? String ?? "", selImgUrl: dict["f_imgNameIOSed"] as? String ?? "", title: dict["f_name"] as? String ?? "", isSelect: isSelect,row:indexPath.row,count: arrayList?.count ?? 0)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectIndex = indexPath.row

         let dict:[String:Any] = self.arrayList?[indexPath.row] ?? [:]
        let gameList :[[String:Any]] = dict["game_list"] as? [[String : Any]] ?? [[:]]
       self.gamePopupView = MXGamePopupView.init(gameArray:gameList, imgUrl: dict["f_imgNameIOSed"] as? String ?? "", typeName: dict["f_name"] as? String ?? "",isHorizontalScreen:self.isHorizontalScreen)
        self.gamePopupView?.callClickBlock({ (dict, selIndex) in
                if self.mXPopupViewPlatformSeltBlock2 !=  nil{
                    self.mXPopupViewPlatformSeltBlock2!(dict,self.selectIndex)//平台列表的下标
                }
        })
        self.collectionView.reloadData()
        let skipTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.timerTick), userInfo: nil, repeats: false)
        RunLoop.main.add(skipTimer, forMode: RunLoop.Mode.common)
        
    }
   
   @objc func timerTick() -> Void{
        self.closePageView()
    }
    @objc func btnClick(_ sender: UIButton) ->Void{
        if mXPopupViewBtnSeltSeltBlock != nil {
            mXPopupViewBtnSeltSeltBlock!(sender.tag)
        }
        self.closePageView()
        
    }
}
